package middleware

import (
	"net/http"
	"rustdesk_api_server/api/response"
	"rustdesk_api_server/utils"

	"github.com/gin-gonic/gin"
)

func AuthorizeJWT() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		const BearerSchema string = "Bearer "
		authHeader := ctx.GetHeader("Authorization")
		if authHeader == "" {
			ctx.JSON(http.StatusOK, response.JsonResult{
				Code:  -1,
				Error: "用户未验证",
			})
			ctx.Abort()
			return
		}
		tokenString := authHeader[len(BearerSchema):]
		if tokenString == "" {
			ctx.JSON(http.StatusOK, response.JsonResult{
				Code:  -1,
				Error: "用户未验证",
			})
			ctx.Abort()
			return
		}
		token, err := utils.ParseToken(tokenString)
		if err != nil {
			ctx.JSON(http.StatusOK, response.JsonResult{
				Code:  -1,
				Error: "错误的Token",
			})
			ctx.Abort()
			return
		}
		ctx.Set("user_id", token.UserId)
		ctx.Next()
	}
}
